<template>
  <van-popup v-model="popShow" position="bottom">
      <van-field v-model="searchVal"  placeholder="搜索" @input="search" v-if="isSearch" input-align="left"/>
      <van-picker
        v-bind="$attrs"
        :columns="columnsData"
        show-toolbar
        @cancel="cancel"
        @confirm="onConfirm"
        @change="change"
        :value-key="this.option.label"
      />
    </van-popup>
</template>

<script>
export default {
  name: 'xyzSelectPopup',
  model: {
    prop: 'show'
  },
  props: {
    columns: {
      type: Array,
      default: function () {
        return []
      }
    },
    option: {
      type: Object,
      default: function () {
        return { label: 'name', value: 'code' }
      }
    },
    show: {
      type: Boolean,
      default: false
    },
    isSearch: {
      type: Boolean,
      default: false
    },
    offOption: { // 关闭option配置key-value;当数据是非集合的数组的时候，开启
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      searchVal: '',
      resultValue: [],
      columnsData: [],
      popShow: this.show
    }
  },
  methods: {
    search (val) {
      if (val) {
        this.columnsData = this.columnsData.filter(item => {
          const data = this.offOption ? item : item[this.option.label]

          return data.indexOf(val) > -1
        })
      } else {
        this.columnsData = JSON.parse(JSON.stringify(this.columns))
      }
    },
    onConfirm (value, index) {
      const data = this.offOption ? value : value[this.option.value]

      this.resultValue = data
      this.popShow = !this.popShow
      this.$emit('confirm', value, index, this.resultValue)
    },
    change (val, index) {
      let data = ''
      if (val) {
        data = this.offOption ? val : val[this.option.value]
      }
      this.$emit('change', val, index, data)
    },
    cancel () {
      this.popShow = !this.popShow
      this.$emit('cancel')
    }
  },
  watch: {
    show (val) {
      this.columnsData = JSON.parse(JSON.stringify(this.columns))
      this.searchVal = ''
      this.popShow = val
    },
    popShow (val) {
      this.$emit('input', val)
    }
  }
}
</script>

<style lang="scss" scoped>
  .dh-field {
    padding: 0 16px;background:#fff;
    .dh-cell.van-cell{padding: 10px 0;}
    .dh-cell.van-cell--required::before{left: -8px;}
    .van-popup{border-radius: 20px 20px 0 0;}
  }
</style>
